<template>
<div>
 <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<el-card class="box-card">
  <el-row :gutter="20">
      <el-col :span="8">
        <el-input placeholder="请输入内容" class="input-with-select" v-model = "queryData.query" clearable @clear="getUsersList">
          <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="addDialog= true">添加用户</el-button>
      </el-col>
  </el-row>
  <el-table :data="users" border stripe>
    <el-table-column type="index" label="#"></el-table-column>
    <el-table-column prop="username" label="用户名"></el-table-column>
    <el-table-column prop="role_name" label="用户角色"></el-table-column>
    <el-table-column prop="email" label="用户邮箱"></el-table-column>
    <el-table-column prop="mobile" label="用户电话"></el-table-column>
    <el-table-column label="状态">
      <template slot-scope='scope'>
        <el-switch v-model="scope.row.mg_state" active-color="#13ce66" inactive-color="#ff4949" @change="switchChange(scope.row)">
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="180">
      <template slot-scope="scope">
        <el-tooltip effect="dark" content="修改信息" placement="top">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row)"></el-button>
        </el-tooltip>
        <el-tooltip effect="dark" content="删除操作" placement="top">
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
        </el-tooltip>
        <el-tooltip effect="dark" content="分配角色" placement="top">
          <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoles(scope.row)"></el-button>
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="queryData.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </el-card>
  <el-dialog
  title="添加用户"
  :visible.sync="addDialog"
  width="30%"
  @close="dialogClose">
  <!-- model用来记录表单的数据 -->
  <el-form :model="addForm" :rules="addFormRules" ref="ruleForm" label-width="70px">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="addForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="addForm.password"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="addForm.email"></el-input>
    </el-form-item>
    <el-form-item label="电话" prop="mobile">
      <el-input v-model="addForm.mobile"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addDialog = false">取 消</el-button>
    <el-button type="primary" @click ='clickAddUsers'>确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="修改用户"
  @close="editUserClose"
  :visible.sync="editUserDialog"
  width="30%">
  <el-form :model="userInfo" ref="editForm" label-width="70px" :rules="addFormRules">
    <el-form-item label="用户名:">
      <el-input v-model="userInfo.username" disabled></el-input>
    </el-form-item>
    <el-form-item label="邮箱:" prop="email">
      <el-input v-model="userInfo.email"></el-input>
    </el-form-item>
    <el-form-item label="电话:" prop="mobile">
      <el-input v-model="userInfo.mobile"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editUserDialog = false">取 消</el-button>
    <el-button type="primary" @click="editUsers">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="分配角色"
  :visible.sync="setRoledialogVisible"
  width="30%"
  @close="value=''">
  <div>
    <p>用户名：{{rolesList.username}}</p>
    <p>当前角色: {{rolesList.role_name}}</p>
  </div>
  分配新角色:
  <el-select placeholder="请选择" v-model="value">
    <el-option
      v-for="item in RolesData"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoledialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRoles">确 定</el-button>
  </span>
</el-dialog>
</div>
</template>

<script>
export default {
  data () {
    //  验证邮箱的规则
    const checkEmail = (rule, value, cb) => {
      //  rule是正则表表达式规则
      //  value是输入框中的值
      //  cb是回调函数
      //  验证邮箱的正则表达式
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (!reg.test(value)) {
        return cb(new Error('邮箱格式不正确'))
      }
      cb()
    }

    const checkMobile = (r, value, cb) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (!reg.test(value)) {
        return cb(new Error('手机号码格式不正确'))
      }
      cb()
    }
    return {
      queryData: {
        //  query是快速搜索
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      users: [],
      total: 0,
      addDialog: false,
      editUserDialog: false,
      userInfo: '',
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [{ required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名在3~6位', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码必须在6~15位', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }]
      },
      setRoledialogVisible: false,
      rolesList: {},
      RolesData: [],
      value: ''
    }
  },

  created () {
    this.getUsersList()
  },

  methods: {
    async getUsersList () {
      const { data: res } = await this.axios.get('users', {
        //  params是给后台传递的数据
        params: this.queryData
      })
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.users = res.data.users
      this.total = res.data.total
    },
    //  选择每页几条
    handleSizeChange (val) {
      //    val 是点击时拿到的数据
      this.queryData.pagesize = val
      // 需要重发送请求 重新渲染页面
      this.getUsersList()
    },
    handleCurrentChange (val) {
      this.queryData.pagenum = val
      this.getUsersList()
    },
    //  通过scope.row拿到一行的数据获取id和mg_state
    async switchChange (userInfo) {
      //  从获取的一行中得到id和状态值
      const { id, mg_state: state } = userInfo
      //  通过接口传给后台 利用模板字符串
      const { data: res } = await this.axios.put(`users/${id}/state/${state}`)
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
    },

    dialogClose () {
      this.$refs.ruleForm.resetFields()
      //  this.$refs是获取表单组件 与表单固定搭配 用于表单重置
    },

    clickAddUsers () {
      this.$refs.ruleForm.validate(async (flag) => {
        if (!flag) return
        const { data: res } = await this.axios.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.addDialog = false
        this.getUsersList()
      })
    },

    async editUser (userInfos) {
      this.editUserDialog = true
      //  JOSN.parse(JSON.stringify(userInfos)) 是简易版的深拷贝
      this.userInfo = JSON.parse(JSON.stringify(userInfos))
    },

    //  关闭对话框事件 重置表单
    editUserClose () {
      this.$refs.editForm.resetFields()
    },

    editUsers () {
      this.$refs.editForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.axios.put(`users/${this.userInfo.id}`, {
          email: this.userInfo.email,
          mobile: this.userInfo.mobile
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('数据修改失败')
        this.editUserDialog = false
        this.$message.success('数据修改成功')
        this.getUsersList()
      })
    },

    removeUserById (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.axios.delete(`users/${id}`)
        if (res.meta.status !== 200) return
        this.$message.success('删除成功!')
        this.getUsersList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    async setRoles (row) {
      this.setRoledialogVisible = true
      this.rolesList = row
      const { data: res } = await this.axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.RolesData = res.data
    },
    async addRoles () {
      if (!this.value) {
        this.$message.error('请选择角色')
      }
      const { data: res } = await this.axios.put(`users/${this.rolesList.id}/role`, { rid: this.value })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新角色失败')
      this.setRoledialogVisible = false
      this.getUsersList()
      this.$message.success('更新角色成功')
    }
  }
}
</script>

<style scoped lang='less'>
.el-select {
  margin-top: 10px;
}
</style>
